package com.bdqn.ch02.sl;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SL04 {
    Document doc=null;
    public void showInfo(){
        //得到DOM解析器的工厂实列
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //获取解析器工厂
        try {
            //从DOM工厂获取DOM解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
            //解析XML文档，得到一个Document，即DOM树
            doc= db.parse("src/dao/PhoneInfo2.xml");
        } catch (ParserConfigurationException e) {
            e.fillInStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
        //创建Brand节点
        Element brandElement =doc.createElement("Brand");
        brandElement.setAttribute("name","三星");
        //创建Type节点
        Element typeElement =doc.createElement("Type");
        typeElement.setAttribute("name","NoteX");
        //添加父子关系
        brandElement.appendChild(typeElement);
        Element phoneElement =(Element) doc.getElementsByTagName("PhoneInfo").item(0);
        phoneElement.appendChild(brandElement);
        //保存XML文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        try {
            Transformer transformer=transformerFactory.newTransformer();
            DOMSource domSource=new DOMSource(doc);
            //设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
            StreamResult result=new StreamResult(new FileOutputStream("src/dao/PhoneInfo2.xml"));
            transformer.transform(domSource,result);
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        SL04 Parse=new SL04();
        Parse.showInfo();
    }
}
